package com.jt.provider.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class TimeAccessInterceptor implements HandlerInterceptor {
    /**
     * 中的拦截器对象，此对象可以在你执行目标controller之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     *
     * 此方法在你执行controller方法之前执行
     * 返回值为true表示放行，可以继续执行request的后续业务
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("===13===");
       //允许在早8点之后，晚9点
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        if (hour<8||hour>=15) {
            /*throw new RuntimeException("请在规定时间内访问");*/
            //设置响应数据编码
            response.setCharacterEncoding("utf-8");
            //告诉客户端响应数据的类型,以及客户端显示内容的编码
            response.setContentType("text/html;charset=utf-8");
            //向客户端响应一个json格式的字符串
            //String str="{\"status\":429,\"message\":\"访问太频繁了\"}";
            Map<String, Object> map = new HashMap<>();
            map.put("status", 430);
            map.put("message", "在早8点之后，晚9点");
            String jsonStr = new ObjectMapper().writeValueAsString(map);
            PrintWriter out = response.getWriter();
            out.print(jsonStr);
            out.flush();
            out.close();
        }
        return true;
    }



}
